import Axios, { InternalAxiosRequestConfig } from "axios";
import { message, Modal } from "ant-design-vue";
import { createVNode } from "vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { NETWORK_ERROR_401, NETWORK_ERROR_500 } from "@/utils/const.ts";

const testUrl = "http://192.168.8.139:7011";
const BASE_URL = import.meta.env.VITE_RES_URL?.toString() || testUrl;

const axios = Axios.create({
  baseURL: BASE_URL,
  timeout: 20000, // 请求超时 20s
});

// 请求拦截
axios.interceptors.request.use(
  (request: InternalAxiosRequestConfig): InternalAxiosRequestConfig => {
    const token = localStorage.getItem("token");
    if (token && request.url !== "/captchaImage" && request.url !== "/login") {
      request.headers.Authorization = `Bearer ${token}`;
    }
    return request;
  },
  error => {
    return Promise.reject(error);
  },
);
// 响应拦截
axios.interceptors.response.use(
  response => {
    const { code, msg } = response.data;

    if (code === NETWORK_ERROR_401) {
      // token 失效
      Modal.info({
        title: "提示",
        icon: createVNode(ExclamationCircleOutlined),
        content: "登录信息已过期",
        okText: "确定",
        onOk() {
          localStorage.clear();
          location.href = "/";
        },
      });
    } else if (code === NETWORK_ERROR_500) {
      message.warning(msg);
      if (
        msg === "验证码错误" ||
        msg === "验证码已失效" ||
        msg === "用户不存在/密码错误"
      ) {
        return {};
      } else {
        return Promise.reject(new Error(msg));
      }
    } else {
      return response.data;
    }
  },
  error => {
    // alert(error)
    if (error instanceof Axios.Cancel) {
      return {};
    }
    message.warning("网络错误");
    return Promise.reject(error);
  },
);

export { axios };
